package org.example.rowing.controller;

import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.ComboBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.util.StringConverter;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.example.rowing.enums.BoatTypeEnum;
import org.example.rowing.service.EventInfoService;
import org.example.rowing.service.RegistrationInfoService;
import org.example.rowing.service.TeamInfoService;
import org.example.rowing.vo.EventVO;
import org.example.rowing.vo.RegistrationExportData;
import org.example.rowing.vo.RegistrationVO;
import org.example.rowing.vo.TeamVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.io.File;
import java.io.FileOutputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Controller
@Slf4j
public class CKRegistrationExportController {
    @FXML
    public ComboBox<EventVO> eventNameField;
    @FXML
    public ComboBox<TeamVO> teamNameField;


    @Autowired
    private TeamInfoService teamInfoService;
    @Autowired
    private EventInfoService eventInfoService;
    @Autowired
    private RegistrationInfoService registrationInfoService;


    // 用于在弹出框初始化时设置事件信息（用于编辑）
    public void initialize(Object object) {
        // 设置转换器，使下拉框只显示 eventName
        eventNameField.setConverter(new StringConverter<EventVO>() {
            @Override
            public String toString(EventVO eventVO) {
                return eventVO == null ? "" : eventVO.getId() + ". " + eventVO.getName();
            }
            @Override
            public EventVO fromString(String string) {
                // 一般不需要转换回对象，可返回 null 或自行实现
                return null;
            }
        });
        teamNameField.setConverter(new StringConverter<TeamVO>() {
            @Override
            public String toString(TeamVO team) {
                return team == null ? "" : team.getId() + ". " + team.getName();
            }
            @Override
            public TeamVO fromString(String string) {
                // 一般不需要转换回对象，可返回 null 或自行实现
                return null;
            }
        });

        loadEventVOS();
        eventNameField.setOnAction(event -> {
            EventVO eventVO = eventNameField.getValue();
            loadTeamVOS(eventVO.getId());
        });
    }

    private void loadEventVOS() {
        List<EventVO> eventVOS = eventInfoService.showEventsByType(BoatTypeEnum.CANOE);
        List<EventVO> eventVOS1 = eventInfoService.showEventsByType(BoatTypeEnum.KAYAK);
        eventVOS.addAll(eventVOS1);
        eventNameField.setItems(FXCollections.observableArrayList(eventVOS));
    }

    private void loadTeamVOS(Long eventId) {
        List<TeamVO> teamVOS = teamInfoService.showTeamsByEventId(eventId);
        teamNameField.setItems(FXCollections.observableArrayList(teamVOS));
    }

    // 保存赛事
    @FXML
    private void handleExportEvent() {
        try {
            // 获取选中的赛事和队伍
            EventVO selectedEvent = eventNameField.getValue();
            TeamVO selectedTeam = teamNameField.getValue();

            if (selectedEvent == null || selectedTeam == null) {
                showAlert("请先选择赛事和队伍");
                return;
            }

            // 获取基础数据
            String eventName = selectedEvent.getName();
            String exportDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy.MM.dd"));
            String teamName = selectedTeam.getName();

            // 获取表格数据（需要实现对应的Service方法）
            RegistrationVO regCondition = new RegistrationVO();
            regCondition.setTeamId(selectedTeam.getId());
            List<RegistrationExportData> exportData = registrationInfoService.getRegistrationExportData(regCondition);

            // 创建Excel工作簿
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("报名确认单");

            // 设置字体样式
            CellStyle headerStyle = workbook.createCellStyle();
            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerFont.setFontHeightInPoints((short)12);
            headerStyle.setFont(headerFont);
            headerStyle.setAlignment(HorizontalAlignment.CENTER);

            // 第一行：赛事名称（合并单元格）
            Row row0 = sheet.createRow(0);
            org.apache.poi.ss.usermodel.Cell cell00 = row0.createCell(0);
            cell00.setCellValue(eventName);
            cell00.setCellStyle(headerStyle);
            sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 3));

            // 第二行：导出日期
            Row row1 = sheet.createRow(1);
            org.apache.poi.ss.usermodel.Cell cell10 = row1.createCell(0);
            cell10.setCellValue("导出时间：" + exportDate);

            // 第三行：队伍名称
            Row row2 = sheet.createRow(2);
            org.apache.poi.ss.usermodel.Cell cell20 = row2.createCell(0);
            cell20.setCellValue("队伍名称：" + teamName);

            // 表格标题行
            Row headerRow = sheet.createRow(3);
            String[] headers = {"","组别", "性别", "项目", "艇数", "参赛队员", "    "};
            for (int i = 0; i < headers.length; i++) {
                org.apache.poi.ss.usermodel.Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(headerStyle);
            }

            // 填充数据行
            int rowNum = 4;
            for (RegistrationExportData reg : exportData) {
                String raceType = reg.getRaceType();
                int boatsNum = 0;
                if (raceType.startsWith("单")) {
                    boatsNum = reg.getAthleteNames().size();
                } else if (raceType.startsWith("双")) {
                    boatsNum = (int) reg.getAthleteNames().size() / 2;
                } else if (raceType.startsWith("四")) {
                    boatsNum = (int) reg.getAthleteNames().size() / 4;
                }

                Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(selectedEvent.getBoatType());
                row.createCell(1).setCellValue(reg.getGroup());
                row.createCell(2).setCellValue(reg.getGender());
                row.createCell(3).setCellValue(reg.getRaceName());
                row.createCell(4).setCellValue(boatsNum);
                row.createCell(5).setCellValue(String.join(", ", reg.getAthleteNames()));
                row.createCell(6).setCellValue("    ");
            }

            // 自动调整列宽
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
                // 获取当前列宽
                int currentWidth = sheet.getColumnWidth(i);
                // 增加额外宽度，例如增加 40% 的宽度
                int extraWidth = (int)(currentWidth * 0.4);
                sheet.setColumnWidth(i, currentWidth + extraWidth);
            }

            // 弹出文件保存对话框
            FileChooser fileChooser = new FileChooser();
            fileChooser.setInitialFileName(eventName + "_报名确认单.xlsx");
            fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Excel 文件", "*.xlsx"));
            File file = fileChooser.showSaveDialog(teamNameField.getScene().getWindow());

            if (file != null) {
                try (FileOutputStream fos = new FileOutputStream(file)) {
                    workbook.write(fos);
                    showAlert("导出成功！");
                }
            }

            workbook.close();
        } catch (Exception e) {
            log.error("导出Excel失败", e);
            showAlert("导出失败：" + e.getMessage());
        }
    }

    private void showAlert(String message) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }

    // 取消操作，关闭弹出框
    @FXML
    private void handleCancel() {
        closeWindow();
    }

    private void closeWindow() {
        Stage stage = (Stage) teamNameField.getScene().getWindow();
        stage.close();
    }
}
